﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.DS
{
    public static partial class problem
    {
        public static dynamic getDSProblemList(int eid, string username, bool god)
        {
            var sql = new Sql.SqlDataContext();
            var total = sql.DSProblem.Count(row => row.eid == eid && (god || !row.disabled));
            IQueryable result;
			if (!string.IsNullOrEmpty(username)) //User
                result = (from p in sql.DSProblem
                          from ps in sql.DSProblemStatistics
                          where p.eid == eid && (god || !p.disabled) && ps.eid == eid && ps.pid == p.pid
                          orderby p.pid
                          join so in sql.DSSolve
                          on new { u = username, eid, p.pid } equals new { u = so.username, so.eid, so.pid }
                          into sos
                          let so = sos.FirstOrDefault()
                          select new
                          {
                              p.eid,
                              p.pid,
                              p.title,
                              p.timeLimit,
                              p.memoryLimit,
                              p.description,
                              ps.accept,
                              ps.submit,
                              status = so == null ? 0 : so.accept > 0 ? 2 : so.submit > 0 ? 1 : 0
                          });
            else //Guest
                result = (from p in sql.DSProblem
                          from ps in sql.DSProblemStatistics
                          where p.eid == eid && !p.disabled && ps.eid == eid && ps.pid == p.pid
                          orderby p.pid
                          select new
                          {
                              p.eid,
                              p.pid,
                              p.title,
                              p.timeLimit,
                              p.memoryLimit,
                              p.description,
                              ps.accept,
                              ps.submit,
                              status = 0
                          });
            return new
            {
                success = true,
                total,
                result
            };
        }
    }
}
